﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ANZ_AIM_BLL.Model;
using ANZ_AIM_GUI.Utils;
using System.IO;
using System.Reflection;
using ANZ_AIM_BLL;
using ANZ_AIM_FRAMEWORK;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using Outlook = Microsoft.Office.Interop.Outlook;
using NPOI.HSSF.Util;
using System.Diagnostics;


namespace ANZ_AIM_GUI
{
    public partial class frmCandidateMaster : Form
    {
        DataTable dtDataEmployeeChangeTemp = new DataTable();

        public Dictionary<string, string> Candidate_FieldLabelDict { get; set; }
        public Dictionary<string, string> Employment_FieldLabelDict { get; set; }

        public EmploymentOffline employment { get; set; }//load data, save local to DB
        public EmploymentOffline employmentTemp { get; set; }//load data, change info
        public MailConfig mailConfig { get; set; }

        public List<EmploymentOffline> listEmploymentOffline = new List<EmploymentOffline>();//for save to DB
        public List<CandidateOffline> listCandidateOffline = new List<CandidateOffline>();

        public List<EmploymentOffline> listEmploymentOfflineTemp = new List<EmploymentOffline>();//for change info
        public frmCandidateMaster()
        {
            InitializeComponent();

            BuildCandidateOfflineLabel();
            BuildEmploymentOfflineLabel();

            RefreshInfo();

            //load mail config
            MailConfigBLL mailConfigBll = new MailConfigBLL();
            mailConfig = mailConfigBll.GetMailConfig();

            if (mailConfig != null)
            {
                txtBranch.Text = mailConfig.Branch;
                txtFloor.Text = mailConfig.Floor;
            }

            //load employment
            LoadDataEmploymentOffline();

            //load column
            dtDataEmployeeChangeTemp.Columns.Add("ProfileID");
            dtDataEmployeeChangeTemp.Columns.Add("BatchFile");
            dtDataEmployeeChangeTemp.Columns.Add("FieldChange");
            dtDataEmployeeChangeTemp.Columns.Add("OldValue");
            dtDataEmployeeChangeTemp.Columns.Add("NewValue");
            dtDataEmployeeChangeTemp.Columns.Add("FirstValue");

            EmploymentOfflineBLL eoBLL = new EmploymentOfflineBLL();
            dtDataEmployeeChangeTemp = eoBLL.GetDataChangeTemp();

            //load emplomentoffline
            DataTable dt = eoBLL.GetEmploymentOfflineTemp();
            foreach (DataRow row in dt.Rows)
            {
                EmploymentOffline eo = new EmploymentOffline();
                eo = UnPackObjectData_Employee(row);
                listEmploymentOfflineTemp.Add(eo);
            }

            //load info change
            lbInfoEmployment.Text = "Number of Change(s) :" + listEmploymentOfflineTemp.Count;

            //load candidateoffline
            CandidateOfflineBLL coBll = new CandidateOfflineBLL();
            listCandidateOffline = coBll.GetCandidateOffline();
            LoadData();
        }

        #region Candidate

        public void LoadData()
        {
            var listBinding = new BindingList<CandidateOffline>(listCandidateOffline);

            dgvDataCandidateOffline.DataSource = null;
            dgvDataCandidateOffline.Columns.Clear();
            dgvDataCandidateOffline.DataSource = listBinding;

            dgvDataCandidateOffline.AutoResizeColumns();

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(CandidateOffline));
            foreach (PropertyDescriptor prop in properties)
            {
                dgvDataCandidateOffline.Columns[prop.Name].HeaderText = Candidate_FieldLabelDict[prop.Name];
                string s = prop.PropertyType.Name;

                if (!s.ToUpper().Equals("STRING"))
                {
                    dgvDataCandidateOffline.Columns[prop.Name].DefaultCellStyle.Format = "dd MMM, yyyy";
                }
            }
        }
        public void BuildCandidateOfflineLabel()
        {
            Candidate_FieldLabelDict = new Dictionary<string, string>();

            Candidate_FieldLabelDict.Add("PersonalCode", "Personal Code");
            Candidate_FieldLabelDict.Add("Channel", "Channel");
            Candidate_FieldLabelDict.Add("FullName_E", "FullName_E");
            Candidate_FieldLabelDict.Add("FullName_V", "FullName_V");
            Candidate_FieldLabelDict.Add("CellPhone", "CellPhone");
            Candidate_FieldLabelDict.Add("DateOfBirth", "Date Of Birth");
            Candidate_FieldLabelDict.Add("College", "College");
            Candidate_FieldLabelDict.Add("Qualification", "Qualification");
            Candidate_FieldLabelDict.Add("IDNumber", "ID Number");
            Candidate_FieldLabelDict.Add("IssuedDate", "Issued Date");
            Candidate_FieldLabelDict.Add("IssuedPlace", "Issued Place");
            Candidate_FieldLabelDict.Add("PermanentAddress", "Permanent Address");
            Candidate_FieldLabelDict.Add("Interviewer", "Interviewer");
            Candidate_FieldLabelDict.Add("InterviewDate", "Interview Date");
            Candidate_FieldLabelDict.Add("TrainingCallStatus", "Training Call Status");
            Candidate_FieldLabelDict.Add("TrainingCallStatusRemarks", "Training Call Status Remarks");

            Candidate_FieldLabelDict.Add("CICSanctionDeliveryDate", "CIC Sanction Delivery Date");
            Candidate_FieldLabelDict.Add("CICSanctionDelivererName", "CIC Sanction Deliverer Name");
            Candidate_FieldLabelDict.Add("CICResult", "CIC Result");
            Candidate_FieldLabelDict.Add("SanctionResult", "Sanction Result");
            Candidate_FieldLabelDict.Add("PECCheckResult", "PEC Check Result");
            Candidate_FieldLabelDict.Add("PECRemarks", "PEC Remarks");

            Candidate_FieldLabelDict.Add("TrainingBatch", "Training Batch");
            Candidate_FieldLabelDict.Add("TrainingDate", "Training Date");
            Candidate_FieldLabelDict.Add("TrainerName", "Trainer Name");
            Candidate_FieldLabelDict.Add("TrainingAttendance", "Training Attendance");
            Candidate_FieldLabelDict.Add("TrainingAttendanceRemarks", "Training Attendance Remarks");
            Candidate_FieldLabelDict.Add("ReTest", "Re Test");
            Candidate_FieldLabelDict.Add("ReTestRequirement", "Re Test Requirement");
            Candidate_FieldLabelDict.Add("TrainingResult", "Training Result");

            Candidate_FieldLabelDict.Add("OBEligible", "OBEligible");
            Candidate_FieldLabelDict.Add("DocumentCompletion", "Document Completion");
            Candidate_FieldLabelDict.Add("DocumentIncompletionRemarks", "Document Incompletion Remarks");
            Candidate_FieldLabelDict.Add("PCReceiptSubmissionDate", "PC Receipt Submission Date");
            Candidate_FieldLabelDict.Add("PCReportSubmissionDate", "PC Report Submission Date");

            Candidate_FieldLabelDict.Add("HiringManagerName", "Hiring Manager Name");
            Candidate_FieldLabelDict.Add("HiringManagerAcknowledgeDate", "Hiring Manager Acknowledge Date");
            Candidate_FieldLabelDict.Add("DelegateApproverName", "Delegate Approver Name");
            Candidate_FieldLabelDict.Add("ApprovingDate", "Approving Date");
            Candidate_FieldLabelDict.Add("OnBoarding", "OnBoarding");
            Candidate_FieldLabelDict.Add("OnBoardingRemarks", "OnBoarding Remarks");
            Candidate_FieldLabelDict.Add("CICSanctionRequestDate", "CIC Sanction RequestDate");
            Candidate_FieldLabelDict.Add("TrainingResultCC", "Training Result CC");
            Candidate_FieldLabelDict.Add("CheckChannel", "Check Channel");
        }


        #region Action
        private void btnAdd_Click(object sender, EventArgs e)
        {
            CandidateOffline co = new CandidateOffline();
            frmCandidateOffline fmCo = new frmCandidateOffline(MiscHelper.FORM_OPMODE_ADD_NEW, co);
            DialogResult result = fmCo.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                co = fmCo.co;
                listCandidateOffline.Add(co);
                LoadData();
                RefreshInfo();
            }
        }
        private void btnSendmail_Click(object sender, EventArgs e)
        {
            try
            {
                if (!validateSendmail())
                {
                    return;
                }

                if (listCandidateOffline != null && listCandidateOffline.Count > 0)
                {
                    string filename = "Candidate_" + txtBranch.Text.Trim() + "_" + txtFloor.Text.Trim() + "_" + DateTime.Now.ToString("MMddyyyy") + ".xls";
                    string fileTemp = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + filename;
                    DataTable dtData = ConvertToDataTable<CandidateOffline>(listCandidateOffline);
                    NPOIHelper.ExportCandidate(dtData, "CANDIDATE", fileTemp, Candidate_FieldLabelDict);
                    sendEMailThroughOUTLOOK(fileTemp, txtBranch.Text.Trim(), txtFloor.Text.Trim());

                    listCandidateOffline.Clear();
                    LoadData();
                }
                else
                {
                    MessageBox.Show("We don't have any candidates to export. Please add new candidate.", Constant.SYS_INFORMATION, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex) { throw; }
        }
        private void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                int selectedRowCount = dgvDataCandidateOffline.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    CandidateOffline co = (CandidateOffline)dgvDataCandidateOffline.SelectedRows[0].DataBoundItem;
                    frmCandidateOffline fmCo = new frmCandidateOffline(MiscHelper.FORM_OPMODE_EDIT, co);
                    DialogResult result = fmCo.ShowDialog(this);
                    if (result == DialogResult.OK)
                    {
                        listCandidateOffline.Remove(co);
                        co = fmCo.co;
                        listCandidateOffline.Add(co);
                        LoadData();
                    }
                }
                else
                {
                    MessageBox.Show("Not candidate is selected.", Constant.SYS_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch (Exception ex)
            {

            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {

            try
            {
                int selectedRowCount = dgvDataCandidateOffline.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    CandidateOffline co = (CandidateOffline)dgvDataCandidateOffline.SelectedRows[0].DataBoundItem;
                    DialogResult result = MessageBox.Show("Are you sure you want to delete this candidate?", "Delete confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                       MessageBoxDefaultButton.Button2);
                    if (result == DialogResult.Yes)
                    {
                        listCandidateOffline.Remove(co);
                        LoadData();
                        RefreshInfo();
                    }
                }
                else
                {
                    MessageBox.Show("Not candidate is selected.", Constant.SYS_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch (Exception ex)
            {

            }


        }

        #endregion

        private bool validateSendmail()
        {
            try
            {
                if (string.IsNullOrEmpty(txtBranch.Text))
                {
                    MessageBox.Show("Branch cannot be empty.", Constant.SYS_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtBranch.Focus();
                    return false;
                }
                if (string.IsNullOrEmpty(txtFloor.Text))
                {
                    MessageBox.Show("Floor cannot be empty.", Constant.SYS_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtFloor.Focus();
                    return false;
                }
                return true;
            }
            catch (Exception ex) { throw; }
        }
        private void sendEMailThroughOUTLOOK(string fileTemp, string branch, string floor)
        {
            try
            {
                // Create the Outlook application.
                Outlook.Application oApp = new Outlook.Application();

                // Create a new mail item.
                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

                // Set HTMLBody. 
                //add the body of the email
                oMsg.HTMLBody = "Content";

                //Add an attachment.
                String sDisplayName = "MyAttachment";
                int iPosition = (int)oMsg.Body.Length + 1;
                int iAttachType = (int)Outlook.OlAttachmentType.olByValue;

                //now attached the file             
                Outlook.Attachment oAttach = oMsg.Attachments.Add(fileTemp, iAttachType, iPosition, sDisplayName);

                if (File.Exists(fileTemp)) File.Delete(fileTemp);

                //Subject line
                oMsg.Subject = "New Candidate" + "-" + branch + "-" + floor + "-" + DateTime.Now.ToString("MMddyyyy");
                oMsg.To = "";
                oMsg.CC = "";
                oMsg.Display(true);

            }
            catch (Exception ex)
            {
            }
        }
        private void RefreshInfo()
        {
            lbInfoListData.Text = "No. of record(s) : " + (listCandidateOffline != null ? listCandidateOffline.Count.ToString() : "0");
        }

        #endregion

        #region Employment
        public void LoadDataEmploymentOffline()
        {
            //load employment offline
            EmploymentOfflineBLL employmentofflineBll = new EmploymentOfflineBLL();
            DataTable dtData = employmentofflineBll.GetEmploymentOfflines();
            dgvData.DataSource = null;
            dgvData.Columns.Clear();
            dgvData.DataSource = dtData;
            dgvData.AutoResizeColumns();

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(EmploymentOffline));
            foreach (PropertyDescriptor prop in properties)
            {
                dgvData.Columns[prop.Name].HeaderText = Employment_FieldLabelDict[prop.Name];
            }
        }
        public void BuildEmploymentOfflineLabel()
        {

            Employment_FieldLabelDict = new Dictionary<string, string>();
            Employment_FieldLabelDict.Add("ID", "ID");// show header when load data from database
            Employment_FieldLabelDict.Add("ProfileID", "Profile ID");
            Employment_FieldLabelDict.Add("CandidateCode", "Candidate Code");
            Employment_FieldLabelDict.Add("CurrentSalesCode", "Current Sales Code");
            Employment_FieldLabelDict.Add("EmploymentFullName", "Employment Full Name");
            Employment_FieldLabelDict.Add("EmploymentFullNameE", "Employment Full Name_E");
            Employment_FieldLabelDict.Add("Role", "Role");
            Employment_FieldLabelDict.Add("Level", "Level");
            Employment_FieldLabelDict.Add("Category", "Category");
            Employment_FieldLabelDict.Add("ProductCategory", "Product Category");
            Employment_FieldLabelDict.Add("Product", "Product");
            Employment_FieldLabelDict.Add("TeamName", "Team Name");
            Employment_FieldLabelDict.Add("TeamLeaderCode", "Team Leader Code");
            Employment_FieldLabelDict.Add("Channel", "Channel");
            Employment_FieldLabelDict.Add("JoiningDate", "Joining Date");
            Employment_FieldLabelDict.Add("PromotionTransferDate", "Promotion/Role Transfer Date");
            Employment_FieldLabelDict.Add("Status", "Status");
            Employment_FieldLabelDict.Add("ContractType", "Contract Type");
            Employment_FieldLabelDict.Add("ContractTerm", "Contract Term");
            Employment_FieldLabelDict.Add("ContractorName", "Contractor Name");
            Employment_FieldLabelDict.Add("ContractSignDate", "Contract Sign Date");
            Employment_FieldLabelDict.Add("ContractExpiryDate", "Contract Expiry Date");
            Employment_FieldLabelDict.Add("BatchFileID", "Batch File ID");
        }
        private EmploymentOffline UnPackObjectData_Employee(DataRow drData)
        {


            employment = new EmploymentOffline();
            employment.ProfileID = drData["ProfileID"].ToString();
            employment.CandidateCode = drData["CandidateCode"].ToString();
            employment.CurrentSalesCode = drData["CurrentSalesCode"].ToString();
            employment.EmploymentFullName = drData["EmploymentFullName"].ToString();
            employment.EmploymentFullNameE = drData["EmploymentFullNameE"].ToString();
            employment.Role = drData["Role"].ToString();
            employment.Level = drData["Level"].ToString();
            employment.Category = drData["Category"].ToString();
            employment.ProductCategory = drData["ProductCategory"].ToString();
            employment.Product = drData["Product"].ToString();
            employment.TeamName = drData["TeamName"].ToString();
            employment.TeamLeaderCode = drData["TeamLeaderCode"].ToString();
            employment.Channel = drData["Channel"].ToString();
            employment.JoiningDate = Convert.ToDateTime(drData["JoiningDate"] != null ? drData["JoiningDate"] : (DateTime?)null);
            employment.PromotionTransferDate = Convert.ToDateTime(drData["PromotionTransferDate"] != null ? drData["PromotionTransferDate"] : (DateTime?)null);
            employment.Status = drData["Status"].ToString();

            employment.ContractType = drData["ContractType"].ToString();
            employment.ContractTerm = drData["ContractTerm"].ToString();
            employment.ContractorName = drData["ContractorName"].ToString();
            employment.ContractSignDate = Convert.ToDateTime(drData["ContractSignDate"] != null ? drData["ContractSignDate"] : (DateTime?)null);
            employment.ContractExpiryDate = Convert.ToDateTime(drData["ContractExpiryDate"] != null ? drData["ContractExpiryDate"] : (DateTime?)null);
            employment.BatchFileID = drData["BatchFileID"].ToString();

            return employment;
        }
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ExcelDialog = new OpenFileDialog();
            ExcelDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
            ExcelDialog.InitialDirectory = @"C:\";
            ExcelDialog.Title = "Select your file excel";
            if (ExcelDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtFileName.Text = ExcelDialog.FileName;
                txtFileName.ReadOnly = true;

                DataTable dtData = NPOIHelper.ImportExceltoDt(txtFileName.Text.Trim(), 0, 2);

                //convert datacolumn
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(EmploymentOffline));
                foreach (PropertyDescriptor prop in properties)
                {
                    if (!prop.Name.Equals("ID"))
                    {
                        dtData.Columns[Employment_FieldLabelDict[prop.Name]].ColumnName = prop.Name;
                    }
                }

                dgvData.DataSource = null;
                dgvData.Columns.Clear();
                dgvData.DataSource = dtData;
                dgvData.AutoResizeColumns();

                //custome header text
                foreach (PropertyDescriptor prop in properties)
                {
                    if (!prop.Name.Equals("ID"))
                    {
                        dgvData.Columns[prop.Name].HeaderText = Employment_FieldLabelDict[prop.Name];
                    }
                }

                //btnsave
                btnSave.Enabled = true;
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {

                DialogResult result = MessageBox.Show("Are you want to save ?", "Save confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                   MessageBoxDefaultButton.Button2);
                if (result == DialogResult.Yes)
                {
                    listEmploymentOffline.Clear();
                    DataTable dtData = (DataTable)dgvData.DataSource;
                    foreach (DataRow dr in dtData.Rows)
                    {
                        employment = UnPackObjectData_Employee(dr);
                        listEmploymentOffline.Add(employment);
                    }

                    if (listEmploymentOffline != null && listEmploymentOffline.Count > 0)
                    {
                        EmploymentOfflineBLL employmentOfflineBll = new EmploymentOfflineBLL();
                        employmentOfflineBll.Save(listEmploymentOffline);
                    }
                    MessageBox.Show("The employees are imported successfully.", Constant.SYS_INFORMATION, MessageBoxButtons.OK, MessageBoxIcon.Information);

                    btnSave.Enabled = false;
                }

            }
            catch (Exception ex)
            {

            }
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string saleCode = txtSaleCode.Text.Trim();
            string fullName = txtFullName.Text.Trim();
            string profileID = txtProfileID.Text.Trim();
            string batchFileID = txtBatchFile.Text.Trim();

            if (string.IsNullOrEmpty(saleCode))
            {
                saleCode = null;
            }
            if (string.IsNullOrEmpty(fullName))
            {
                fullName = null;
            }
            if (string.IsNullOrEmpty(profileID))
            {
                profileID = null;
            }
            if (string.IsNullOrEmpty(batchFileID))
            {
                batchFileID = null;
            }

            EmploymentOfflineBLL employmentOfflineBll = new EmploymentOfflineBLL();
            DataTable dtData = employmentOfflineBll.Search(saleCode, fullName, profileID, batchFileID);

            dgvData.DataSource = null;
            dgvData.Columns.Clear();
            dgvData.DataSource = dtData;
            dgvData.AutoResizeColumns();

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(EmploymentOffline));
            foreach (PropertyDescriptor prop in properties)
            {
                dgvData.Columns[prop.Name].HeaderText = Employment_FieldLabelDict[prop.Name];
            }

        }
        private void dgvData_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                int selectedRowCount = dgvData.Rows.GetRowCount(DataGridViewElementStates.Selected);
                if (selectedRowCount > 0)
                {
                    DataRow dr = ((DataRowView)dgvData.SelectedRows[0].DataBoundItem).Row;
                    employmentTemp = UnPackObjectData_Employee(dr);
                    loadFieldName();
                    txtProfileIDChange.Text = employmentTemp.ProfileID;
                    txtBatchFileChange.Text = employmentTemp.BatchFileID;
                    txtNewValue.Text = "";
                }
            }
            catch (Exception ex)
            {

            }
        }
        private void loadFieldName()
        {
            cbField.Items.Clear();
            if (employmentTemp != null)
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(EmploymentOffline));

                foreach (PropertyDescriptor prop in properties)
                {
                    cbField.Items.Add(prop.Name);
                }
            }
        }
        private void btnUpdateEmployment_Click(object sender, EventArgs e)
        {
            if (chbBatchFile.Checked)
            {
                //save in datatable -> view 
                DataRow dr = dtDataEmployeeChangeTemp.NewRow();
                DataRow[] foundRows = dtDataEmployeeChangeTemp.Select("BatchFile= '" + txtBatchFileChange.Text + "' AND FieldChange = '" + cbField.Text + "'");
                if (foundRows.Length > 0)
                {
                    foundRows[0]["NewValue"] = txtNewValue.Text;
                }
                else
                {
                    dr["BatchFile"] = txtBatchFileChange.Text;
                    dr["FieldChange"] = cbField.Text;
                    dr["OldValue"] = txtOldValue.Text;
                    dr["NewValue"] = txtNewValue.Text;
                    dr["FirstValue"] = txtOldValue.Text;
                    dtDataEmployeeChangeTemp.Rows.Add(dr);
                }

                //save in listtemp-> export
                List<EmploymentOffline> listResult = listEmploymentOfflineTemp.FindAll(item => item.BatchFileID == txtBatchFileChange.Text);
                if (listResult.Count > 0)
                {
                    foreach (EmploymentOffline eo in listResult)
                    {
                        eo.GetType().GetProperty(cbField.Text).SetValue(eo, txtNewValue.Text, null);
                    }
                }
                else
                {
                    EmploymentOfflineBLL eoBLL = new EmploymentOfflineBLL();
                    DataTable dt = eoBLL.GetEmploymentOfflineByBatchFile(txtBatchFileChange.Text);
                    foreach (DataRow row in dt.Rows)
                    {
                        row[cbField.Text] = txtNewValue.Text;
                        EmploymentOffline eo = new EmploymentOffline();
                        eo = UnPackObjectData_Employee(row);
                        listEmploymentOfflineTemp.Add(eo);
                    }
                }
                lbInfoEmployment.Text = "Number of Change(s) :" + listEmploymentOfflineTemp.Count;
                MessageBox.Show("Change info saved.", Constant.SYS_INFORMATION, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (txtNewValue.Text != null && employmentTemp != null)
            {
                //save in listtemp -> export 
                int index = listEmploymentOfflineTemp.FindIndex(f => f.ProfileID.Equals(employmentTemp.ProfileID));
                if (index >= 0)
                {
                    employmentTemp = listEmploymentOfflineTemp[index];
                    employmentTemp.GetType().GetProperty(cbField.Text).SetValue(employmentTemp, txtNewValue.Text, null);
                }
                else
                {
                    employmentTemp.GetType().GetProperty(cbField.Text).SetValue(employmentTemp, txtNewValue.Text, null);
                    listEmploymentOfflineTemp.Add(employmentTemp);
                }

                //save in datatable -> view 
                DataRow dr = dtDataEmployeeChangeTemp.NewRow();
                DataRow[] foundRows = dtDataEmployeeChangeTemp.Select("ProfileID= '" + employmentTemp.ProfileID + "' AND FieldChange = '" + cbField.Text + "'");
                if (foundRows.Length > 0)
                {
                    foundRows[0]["NewValue"] = txtNewValue.Text;
                }
                else
                {
                    dr["ProfileID"] = employmentTemp.ProfileID;
                    dr["FieldChange"] = cbField.Text;
                    dr["OldValue"] = txtOldValue.Text;
                    dr["NewValue"] = txtNewValue.Text;
                    dr["FirstValue"] = txtOldValue.Text;
                    dtDataEmployeeChangeTemp.Rows.Add(dr);
                }

                lbInfoEmployment.Text = "Number of Change(s) :" + listEmploymentOfflineTemp.Count;
                MessageBox.Show("Change info saved.", Constant.SYS_INFORMATION, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Nothing to change.", Constant.SYS_INFORMATION, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
        private void btnViewChange_Click(object sender, EventArgs e)
        {
            if (dtDataEmployeeChangeTemp != null && dtDataEmployeeChangeTemp.Rows.Count > 0)
            {
                frmEmployeeOffline frmEmploymentChange = new frmEmployeeOffline(dtDataEmployeeChangeTemp, listEmploymentOfflineTemp);
                DialogResult result = frmEmploymentChange.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    dtDataEmployeeChangeTemp = frmEmploymentChange.dtEmploymentOfflineTemp;
                    listEmploymentOfflineTemp = frmEmploymentChange.listEmploymentOfflineTemp;
                }
            }
            else
            {
                MessageBox.Show("Nothing change to view.", Constant.SYS_INFORMATION, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
        private void btnExportChange_Click(object sender, EventArgs e)
        {
            foreach (EmploymentOffline eo in listEmploymentOfflineTemp)
            {
                DataRow[] foundRows = dtDataEmployeeChangeTemp.Select("ProfileID= '" + eo.ProfileID + "' OR BatchFile= '" + eo.BatchFileID + "'");
                if (foundRows.Length == 0)
                {
                    listEmploymentOfflineTemp.Remove(eo);
                }
            }

            DataTable dt = new DataTable();
            dt = ConvertToDataTable(listEmploymentOfflineTemp);
            NPOIHelper.ExportCandidate(dt, "CANDIDATE", "F:\\test.xls", Employment_FieldLabelDict);

            //NPOIHelper.ExportDTtoExcel(dt, "abc", "F:\\test.xls");

            listEmploymentOfflineTemp.Clear();
            dtDataEmployeeChangeTemp.Rows.Clear();
        }
        private void formatDatetimeForDgv(DataGridView dgvData)
        {

            //dgvData.Columns["Joining Date"].DefaultCellStyle.Format = "dd MMM, yyyy";
            //dgvData.Columns["Promotion Transfer Date"].DefaultCellStyle.Format = "dd MMM, yyyy";
            //dgvData.Columns["Contract SignDate"].DefaultCellStyle.Format = "dd MMM, yyyy";
            // dgvData.Columns["Contract ExpiryDate"].DefaultCellStyle.Format = "dd MMM, yyyy";

            ////foreach (DataGridViewColumn dc in dgvData.Columns)
            ////{
            ////    dgvData.Columns[dc.Name].HeaderText = Employee_FieldLabelDict.FirstOrDefault(x=>x.Value.Equals(dc.Name)).Key;
            ////}
        }
        private void cbField_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtNewValue.Text = "";
            if (employmentTemp != null)
            {
                txtOldValue.Text = employmentTemp.GetType().GetProperty(cbField.Text).GetValue(employmentTemp, null).ToString();
            }
        }

        #endregion

        #region Email
        private void btnUpdateMail_Click(object sender, EventArgs e)
        {
            if (!validateSendmail())
            {
                return;
            }
            if (mailConfig == null)
            {
                mailConfig = new MailConfig();
            }

            mailConfig.Branch = txtBranch.Text.Trim();
            mailConfig.Floor = txtFloor.Text.Trim();
            mailConfig.CreatedDate = MiscHelper.DateTimeToShort(DateTime.Now);
            mailConfig.LastUpdate = MiscHelper.DateTimeToShort(DateTime.Now);

            MailConfigBLL mailConfigBll = new MailConfigBLL();
            mailConfigBll.Save(mailConfig);
        }
        #endregion

        public DataTable ConvertToDataTable<T>(List<T> data)
        {
            PropertyDescriptorCollection properties =
               TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;

        }

        private void frmCandidateMaster_FormClosed(object sender, FormClosedEventArgs e)
        {
            CandidateOfflineBLL coBLL = new CandidateOfflineBLL();
            coBLL.Save(listCandidateOffline);

            EmploymentOfflineBLL eoBLL = new EmploymentOfflineBLL();
            eoBLL.SaveTemp(listEmploymentOfflineTemp);
            eoBLL.SaveChangeTemp(dtDataEmployeeChangeTemp);
        }



    }
}
